import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import javax.sound.midi.*;
import java.net.URL;
import java.net.MalformedURLException;
import java.io.IOException;
/**
 * Audioplayer plays midi files.
 * 
 * @author Ninto <i>(original: Anthony Hoang)
 * @version 0.1
 */
public class music extends Actor
{
    /**The sequencer*/
    Sequencer sequencer;
    /**The name of the music-file*/
    private String file;
    /**Whether this is a new file or not*/
    private boolean newPlay = false;
    
    /**
     * Create a new audioPlayer.
     * @param fileName The name of the file.
     */
    public music(String fileName)
    {
        file = "sounds/"+fileName+".mid";
        load(file);
    }
    
    /**
     * Act - do whatever the audioPlayer wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        if(newPlay) {
            sequencer.start();
            newPlay = false;
        }
        if (sequencer.getTickPosition() == sequencer.getTickLength())
        {
            sequencer.setTickPosition(0);
            sequencer.start();
        }
    }
    
    /**
     * Set the song to be played.
     * 
     * @param fileName the name of the song. <i>(has to be in the  sounds-folder)
     */
    public void setSong(String fileName) {
        sequencer.stop();
        file = "sounds/"+fileName+".mid";
        load(file);
        newPlay = true;
    }
    
    /**
     * Load a new file.
     * 
     * @param fileName the name of the file. (requires folderName/fileName.mid).
     */
    private void load(String fileName) {
        try {
            URL url = getClass().getClassLoader().getResource(fileName);
            if(url == null)
            throw new IOException("File not found: " + fileName);
            Sequence sequence = MidiSystem.getSequence(url);
            
            // Create a sequencer for the sequence
            sequencer = MidiSystem.getSequencer();
            sequencer.open();
            sequencer.setSequence(sequence);
        }
        catch (MalformedURLException e) {}
        catch (IOException e) {}
        catch (MidiUnavailableException e) {}
        catch (InvalidMidiDataException e) {}
    }
}
